package uk.co.agileworks.bidpirate.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import uk.co.agileworks.bidpirate.model.User;

@Controller
@RequestMapping("/login.html")
public final class LoginForm extends ControllerHelper {

	static final String FORM = "login";
	static final String SUCCESS = "redirect:/listBids.html";

	@Resource
	private Validator<User> userValidator;

	@RequestMapping(method = RequestMethod.GET)
	public void getForm(Model model) {
		model.addAttribute(getUserSession().getUser());
	}

	@RequestMapping(method = RequestMethod.POST)
	public String postForm(@ModelAttribute("user") User user, Errors errors) {
		if (userValidator.validate(user, errors) && !getBusinessLogic().logIn(user)) {
			errors.reject("login.invalid");
		}
		return errors.hasErrors() ? FORM : SUCCESS;
	}

}
